package com.huixuebao.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.huixuebao.common.intercepors.JWTInterceptor;
import org.springframework.http.HttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SING="!Q@W#E$R";

    /**
     * 生成token  header.payload.sing
     */
    public static String getToken(Map<String,String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//默认7天过期

        //创建jwt buidler
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));//sign
        //保存进数据库

        return token;
    }

    /**
     * 验证token  合法性
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 获取用户id
     */
    public static String getUserId(HttpServletRequest request){
        String token = request.getHeader("access_token");
        return verify(token).getClaim("userId").asString();
    }
    /**
     * 获取用户id
     */
    public static String getUserType(HttpServletRequest request){
        String userType = request.getHeader("userType");
        return userType;
    }
}
